package ajaxjs.data.user;

import java.sql.Connection;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ajaxjs.data.entry.Entry;
import ajaxjs.data.service.BaseService;
import ajaxjs.Util;
public class Login extends BaseService{

	public static String name = "用户";
	public static String id = "user";
	public Entry pojo = new UserEntry();
	
	// 只有 方法 才可以获取当前实例的
	public UserEntry getPojo(){
		return (UserEntry)this.pojo;
	}
	
	@Override
	public String getTableName() {
		// TODO Auto-generated method stub
		return id;
	}

	@Override
	public String getName() {
		return name;
	}
	@Override
	public String getId() {
		return id;
	}
	
	public HttpSession session = null; 
	public HttpServletResponse response = null;
	
	@Override
	public void setObjs(HttpServletRequest request, Connection jdbcConn){
		super.setObjs(request, jdbcConn);
		session = request.getSession();
	}
	/**
	 * 是否已登录.如果已经设置过了session属性，则肯定不能为空  
	 * @return
	 */
	public boolean isLogined(){
		return isLoginedBySession(this.session);
	}

	public static boolean isLoginedBySession(HttpSession session){
		return session != null && session.getAttribute("uid") != null;
	}
	
	/**
	 * 记住账号和密码@todo 密码不能明文的
	 * @param userName
	 * @param password
	 */
	private void rememberMe(String userName, String password){
		String host = request.getServerName();  
		Cookie cookie;
		cookie = new Cookie("SESSION_LOGIN_USERNAME", userName); // 保存用户名到Cookie  
		cookie.setPath("/");  
		cookie.setDomain(host);  
		cookie.setMaxAge(99999999);  
		response.addCookie(cookie);  

		// 保存密码到Cookie，注意需要加密一下  
		cookie = new Cookie("SESSION_LOGIN_PASSWORD", password);  
		cookie.setPath("/");  
		cookie.setDomain(host);  
		cookie.setMaxAge(99999999);  
		response.addCookie(cookie);
	}
	
	/**
	 * 登出账户
	 */
	public void logout(){
		session.invalidate();   // 让所有 session 失效。  
		// 清除 cookie 保存的密码			
		if(response != null){
			String host = request.getServerName();
			Cookie cookie = new Cookie("SESSION_LOGIN_PASSWORD", "");   
			cookie.setPath("/");   
			cookie.setMaxAge(99999999);   
			cookie.setDomain(host);   
			response.addCookie(cookie);  
		}
	}
	
	public String failLogin_Reason = null;
	// 进行登录
	public void login(){
		// 会员登录的表单信息。
		String  username = request.getParameter("name"), 
				requestPassword = request.getParameter("password");
		try{
			Util.isEmptyString(username, "没有用户名参数！");
			Util.isEmptyString(requestPassword, "没有密码参数！");
			
//		if(!new VcodeImg().isPass(  (PageContext) request.getSession().getServletContext() ))throw new NullPointerException("验证码错误！");
			
			System.out.println(username + "尝试进行登录，使用密码：" + requestPassword);
			
			if(login(username, requestPassword)){
				request.setAttribute("msg", "登录成功！");
			}
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute("errMsg", "登录异常！" + e.getMessage());
		}
	}
	public boolean login (String username, String password){
		find(" name = '" + username + "'");
		UserEntry user = getPojo();
		String passwordInDB = user.password.value.toString();
		
		if(passwordInDB.equals(password)){
			// 登录成功！设置session
			
			session.setAttribute("uid", ajaxjs.js.SimpleJsEngine.jsNumber2int(user.id.value));
			session.setAttribute("username", username);
			
			// 记录登录时间？			
			System.out.println("用户" + username + "已经登录");
			
			// 是否保存
			String rememberMe = request.getParameter("rememberMe");
			if(rememberMe != null && rememberMe.equals("on"))
				rememberMe(username, password);
			
			return true;
		}else{
			// System.out.println("用户：" + username + "登录密码错误：" + password);
			request.setAttribute("errMsg", "密码错误");
			
			return false;
		}
	}
	
	/**
	 * 如果已保存密码，则从给cookie 获取账号和密码进行登录
	 */
	public void loginByCookie(){
		if(this.isLogined())return;

		String usernameCookie = null;  
		String passwordCookie = null;  
		
		Cookie[] cookies;
		cookies = request.getCookies();  
		
		if (cookies != null) {  
			for (Cookie cookie : cookies) {  
				if ("SESSION_LOGIN_USERNAME".equals(cookie.getName()))
					usernameCookie = cookie.getValue(); // 得到cookie的用户名  
				if ("SESSION_LOGIN_PASSWORD".equals(cookie.getName()))
					passwordCookie = cookie.getValue(); // 得到cookie的密码  
			}  
			if (usernameCookie != null && passwordCookie != null) { // 如果存在  
	 			if(this.login(usernameCookie, passwordCookie))
	 				System.out.println("用户" + usernameCookie + "从 Cookies 自动登录成功！");
	 			else
	 				System.out.println("用户" + usernameCookie + "从 Cookies 自动登录失败！保存了错误的账号和密码？");
			}  
		} 
	}

	/**
	 * 限制次数
	 */
//	private int loginCounter(){	
//		int overHits = 5;
//		Object limit = this.session.getAttribute("WrongLitmit");
//		
//		if (this.session.getAttribute("WrongLitmit") != null){
//			this.session.setAttribute("WrongLitmit", ++limit);
//		}else{
//			this.session.setAttribute("WrongLitmit", 1);
//		}
		
//		if (limit < overHits || limit > overHits) {
//			// Max TRY number is 10.make a 区间! when pressed "back" button, will
//			// coutiune last session!,
//			return overHits - limit; // return a number which remains credit
//		} 
//		return 0;
//	}
	
	/**
	 * 获取最后十名来访者
	 */
//	private void lastVisitors(){
//		Application.Lock();
//		// 创建或者取得最近10个Application数组
//		var lastVisitors = Application.staticObjects("dict").Item('edk_lastVisitors');
//		var len = lastVisitors.length;
//		if(len > 9){
//			len = 9;
//			for(var i = 0; i < len;){
//				lastVisitors[i] = lastVisitors[++i];
//			}
//		}
//		lastVisitors[len] = {
//			 ip 		: Request.ServerVariables("REMOTE_ADDR")()		// IP地址
//			,browser	: Request.ServerVariables("HTTP_USER_AGENT")()	// 浏览器
//			,date		: new Date										// 访问时间
//		};
//		
//		Application.UnLock();
//	}
}